import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    items: [
      { name: '手机', price: 1000, quantity: 1 },
      { name: '电脑', price: 2000, quantity: 1 },
      { name: '键盘', price: 200, quantity: 2 }
    ]
    
  },
  getters: {
    total(state) {
      return state.items.reduce((total, item) => total + item.price * item.quantity, 0);
    }
  },
  mutations: {
    ADD_ITEM(state, item) {
      const existingItem = state.items.find(i => i.name === item.name);
      if (existingItem) {
        existingItem.quantity++;
      } else {
        state.items.push({ ...item, quantity: 1 });
      }
    },
    REMOVE_ITEM(state, name) {
      const index = state.items.findIndex(i => i.name === name);
      if (index !== -1) {
        state.items.splice(index, 1);
      }
    },
    INCREMENT_QUANTITY(state, name) {
      const existingItem = state.items.find(i => i.name === name);
      if (existingItem) {
        existingItem.quantity++;
      }
    },
    DECREMENT_QUANTITY(state, name) {
      const existingItem = state.items.find(i => i.name === name);
      if (existingItem && existingItem.quantity > 1) {
        existingItem.quantity--;
      }
    }
  },
  actions: {
    addItem(context, item) {
      context.commit('ADD_ITEM', item);
    },
    removeItem(context, name) {
      context.commit('REMOVE_ITEM', name);
    },
    incrementQuantity(context, name) {
      context.commit('INCREMENT_QUANTITY', name);
    },
    decrementQuantity(context, name) {
      context.commit('DECREMENT_QUANTITY', name);
    }
  },
  modules: {
  }
})
